const db = require('../db/index.js')



// 存储用户连接的 Map，键为 uid，值为响应对象
const sseConnections = new Map()


// 处理sse连接
// GET /sse/cnt
const sseConnect = (req, res) => {
    // 设置 SSE 响应头
    res.setHeader('Content-Type', 'text/event-stream')
    res.setHeader('Cache-Control', 'no-cache')
    res.setHeader('Connection', 'keep-alive')
    res.flushHeaders() // 立即发送头信息

    // 从请求头获取认证 token
    const uid = req.user.uid

    // 将连接添加到 Map
    sseConnections.set(uid, res)
    console.log(`user ${uid} connected, online: ${sseConnections.size}`)
    // 监听客户端断开连接
    req.on('close', () => {
        sseConnections.delete(uid)
        console.log(`user ${uid} disconnected, online: ${sseConnections.size}`)
    })
    req.on('end', () => {
        sseConnections.delete(uid)
        console.log(`user ${uid} disconnected, online: ${sseConnections.size}`)
    })

    // 发送连接成功的自定义事件
    res.write(`event: connected\n`)
    res.write(`data: ${JSON.stringify({
        code: 0,
        msg: 'sse连接成功',
        timestamp: new Date().toISOString()
    })}\n\n`)



    // 定时发送心跳事件（保持连接活跃）
    const heartbeatInterval = setInterval(() => {
        if (sseConnections.has(uid)) {
            res.write(`event: heartbeat\n`)
            res.write(`data: ${JSON.stringify({ timestamp: new Date().toISOString() })}\n\n`)
        } else {
            clearInterval(heartbeatInterval)
        }
    }, 60000) // 每 30 秒发送一次心跳
}

// 发送普通消息
// POST /sse/send
const sendCommonMsg = (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.resUid || !req.body.sendMsg) {
        return res.cc('请求体必要信息不能为空', 10)
    }
    const sendUid = req.user.uid, { resUid, sendMsg } = req.body

    const sendConnection = sseConnections.get(sendUid)
    const resConnection = sseConnections.get(resUid)
    if (!sendConnection) {
        return res.cc('当前sse未连接', 1)
    }


    try {
        // 发送自定义事件
        sendConnection.write(`event: commonMsg\n`)
        sendConnection.write(`data: ${JSON.stringify({
            sendUid,
            resUid,
            sendMsg,
            timestamp: new Date().toISOString(),
            source: 'system'
        })}\n\n`)

        if (resConnection) {
            resConnection.write(`event: commonMsg\n`)
            resConnection.write(`data: ${JSON.stringify({
                sendUid,
                resUid,
                sendMsg,
                timestamp: new Date().toISOString(),
                source: 'system'
            })}\n\n`)
        }

        // 写入聊天记录
        // ...


        res.send({
            code: 0,
            msg: '发送消息成功',
            data: {
                resUid,
                sendMsg
            }
        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: sendCommonMsg-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

module.exports = {
    sseConnect,
    sendCommonMsg
}